package com.flyme.module.base.provider.controller;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.flyme.common.core.constants.CommonConstants;
import com.flyme.common.core.model.ResultBody;
import com.flyme.common.core.model.query.CriteriaQuery;
import com.flyme.common.core.model.query.PagerInfo;
import com.flyme.common.core.model.query.PqGrid;
import com.flyme.common.core.security.OpenHelper;
import com.flyme.common.core.security.OpenUserAuth;
import com.flyme.common.core.utils.ObjectUtils;
import com.flyme.core.base.supper.controller.BaseController;
import com.flyme.core.base.supper.entity.EntityMap;
import com.flyme.module.base.client.api.SysStaffRemoteService;
import com.flyme.module.base.client.dto.SysRankDto;
import com.flyme.module.base.client.dto.SysUserDto;
import com.flyme.module.base.client.dto.UserabilityDto;
import com.flyme.module.base.client.entity.*;
import com.flyme.module.base.client.enums.EducationEnum;
import com.flyme.module.base.client.enums.PostEnum;
import com.flyme.module.base.client.enums.ProfessionEnum;
import com.flyme.module.base.client.enums.RankEnum;
import com.flyme.module.base.provider.service.*;
import com.flyme.module.exam.client.enums.AbilityItemEnum;
import com.flyme.module.exam.provider.service.BusUserabilityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 企业端-员工管理

 */
@Api(tags = "员工管理")
@RestController
public class SysStaffController extends BaseController<SysUserService, SysUser> implements SysStaffRemoteService {

    @Autowired
    private SysWorkCourseService workCourseService;
    @Autowired
    private SysEducationService educationService;
    @Autowired
    private BusUserabilityService userabilityService;
    @Autowired
    private SysAccountService sysAccountService;
    @Autowired
    private SysBalanceService balanceService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysBlacklistService blacklistService;
    @Autowired
    private SysVipTypeService vipTypeService;
    @Autowired
    private SysDeptService deptService;
    @Autowired
    private SysCompanyService companyService;

    /**
     * 员工列表
     *
     * @return
     */
    @ApiOperation(value = "员工列表", notes = "员工列表")
    public ResultBody list(@ModelAttribute PagerInfo pagerInfo, @ModelAttribute SysUser user) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        List<Long> deptIds = deptService.getDeptId(userAuth.getUserId());
        CriteriaQuery cq = new CriteriaQuery<EntityMap>(pagerInfo);
        cq.select("u.id", "u.jobNo","u.nickName", "u.userName", "dept.deptName","u.nickName", "u.createTime", "u.mobile","u.hiredate", "u.idCard",
            "(SELECT bu.abilityScore FROM bus_userability bu LEFT JOIN exa_examtype e ON e.id = bu.abilityItemId WHERE bu.userId = u.id AND e.examTypeCode = '" + AbilityItemEnum.serve.code + "') serveScore",
            "(SELECT bu.abilityScore FROM bus_userability bu LEFT JOIN exa_examtype e ON e.id = bu.abilityItemId WHERE bu.userId = u.id AND e.examTypeCode = '" + AbilityItemEnum.finance.code + "') financeScore",
            "(SELECT bu.abilityScore FROM bus_userability bu LEFT JOIN exa_examtype e ON e.id = bu.abilityItemId WHERE bu.userId = u.id AND e.examTypeCode = '" + AbilityItemEnum.maintain.code + "') maintainScore",
            "(SELECT bu.abilityScore FROM bus_userability bu LEFT JOIN exa_examtype e ON e.id = bu.abilityItemId WHERE bu.userId = u.id AND e.examTypeCode = '" + AbilityItemEnum.develop.code + "') developScore",
            "(SELECT bu.abilityScore FROM bus_userability bu LEFT JOIN exa_examtype e ON e.id = bu.abilityItemId WHERE bu.userId = u.id AND e.examTypeCode = '" + AbilityItemEnum.marketing.code + "') marketingScore",
            "(SELECT bu.abilityScore FROM bus_userability bu LEFT JOIN exa_examtype e ON e.id = bu.abilityItemId WHERE bu.userId = u.id AND e.examTypeCode = '" + AbilityItemEnum.manage.code + "') manageScore",
            "(SELECT bu.abilityScore FROM bus_userability bu LEFT JOIN exa_examtype e ON e.id = bu.abilityItemId WHERE bu.userId = u.id AND e.examTypeCode = '" + AbilityItemEnum.education.code + "') educationScore",
            "(SELECT bu.abilityScore FROM bus_userability bu LEFT JOIN exa_examtype e ON e.id = bu.abilityItemId WHERE bu.userId = u.id AND e.examTypeCode = '" + AbilityItemEnum.work.code + "') workScore",
            "(SELECT bu.abilityScore FROM bus_userability bu LEFT JOIN exa_examtype e ON e.id = bu.abilityItemId WHERE bu.userId = u.id AND e.examTypeCode = '" + AbilityItemEnum.synthesis.code + "') synthesisScore",
            "(SELECT COUNT(id) FROM sys_blacklist WHERE userId = u.id AND companyId = " + userAuth.getCompanyId() + ") isBlack");
        cq.like("u.userName", user.getUserName());
        cq.like("u.mobile", user.getMobile());
        if (OpenHelper.hasRole("hr") && deptIds.size()>0) {
            cq.in("u.deptId", deptIds);
        }
        if(ObjectUtils.isNotEmpty(user.getDeptId())){
            cq.eq("u.deptId", user.getDeptId());
        }
        if(ObjectUtils.isNotEmpty(user.getIdCard())){
            cq.like("u.idCard", user.getIdCard());
        }
        cq.eq("u.userType", "UT_STUDENT");
        cq.eq("u.companyId", userAuth.getCompanyId());
        cq.ge("u.hiredate", user.getStartDate());
        cq.le("u.hiredate", user.getEndDate());
        cq.createAlias("dept", "dept");
        PqGrid pqGrid = bizService.pageList(cq);
        EntityMap map = new EntityMap();
        boolean tag = true;
        if (OpenHelper.hasRole("hr")) {
            tag = false;
        }
        map.put("pqGrid", pqGrid);
        map.put("loginType", tag);
        map.put("companyId", userAuth.getCompanyId());
        return ResultBody.success(map);
    }


    /**
     * 员工详情
     */
    @ApiOperation(value = "员工详情", notes = "员工详情")
    public ResultBody staffDetail(@PathVariable Long userId) {
        EntityMap map = new EntityMap();
        CriteriaQuery cq = new CriteriaQuery<EntityMap>(new PagerInfo());
        cq.select("u.*,dept.deptName userDeptName");
        cq.eq("u.id", userId);
        cq.createAlias("dept", "dept");
        PqGrid pqGrid = bizService.pageList(cq);
        map.put("staff", pqGrid.getRows());
        List<SysWorkCourse> woekList = workCourseService.selectByUserId2(userId);
        for (SysWorkCourse work : woekList) {
            work.setPosition(PostEnum.getText(work.getPosition()));
        }
        map.put("work", woekList);
        List<SysEducation> educationlist = educationService.selectByUserId(userId);
        for (SysEducation education : educationlist) {
            education.setEducation(EducationEnum.getText(education.getEducation()));
            education.setMajor(ProfessionEnum.getText(education.getMajor()));
            education.setGrade(RankEnum.getText(education.getGrade()));
        }
        map.put("education", educationlist);
        return ResultBody.success(map);
    }


    /**
     * 员工项目分数
     */
    @ApiOperation(value = "员工测评分数", notes = "员工测评分数")
    public ResultBody staffScore(@PathVariable Long userId) {
        CriteriaQuery cq = new CriteriaQuery<EntityMap>(new PagerInfo());
        cq.select("e.examTypeName,d.duanName,b.id,b.abilityScore,e.examTypeCode,b.hrScore");
        cq.eq("b.userId", userId);
        cq.createAlias("examtype", "e");
        cq.createAlias("duan", "d");
        cq.orderByAsc("b.abilityItemId");
        PqGrid pqGrid = userabilityService.pageList(cq);
        return ResultBody.success(pqGrid);
    }

    /**
     * 添加员工
     */
    @ApiOperation(value = "添加员工", notes = "添加员工")
    public ResultBody addStaff(@ModelAttribute SysUserDto user) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();//企业
        SysCompany company = companyService.getById(userAuth.getCompanyId());
        if (ObjectUtils.isEmpty(company)) {
            return ResultBody.failed("未知错误,请联系管理员");
        }
        SysUser staff = bizService.findByMobile(user.getMobile());
        if(ObjectUtils.isNotEmpty(staff)){
            Long companyId=staff.getCompanyId();
            if(ObjectUtils.isNotEmpty(companyId)){
                return ResultBody.failed("添加失败:员工处于在职状态");
            }
        }
        //查询该企业员工数量
        Integer staffNum = bizService.count(q().eq("companyId", userAuth.getCompanyId()));
        Integer staffNumCompany = ObjectUtils.gertIngeter(company.getStaffNum(), 0);
        if (staffNum >= staffNumCompany) {
            return ResultBody.failed("员工数量超出限制");
        }

        if (ObjectUtils.isNotEmpty(staff)) {//根据手机号查询到员工
            staff.setEmail(user.getEmail());
            staff.setDeptId(user.getDeptId());
            staff.setSex(user.getSex());
            staff.setJobNo(user.getJobNo());
            staff.setCompanyId(userAuth.getCompanyId());
            staff.setUserName(user.getUserName());
            staff.setHiredate(user.getHiredate());
            boolean a = bizService.saveOrUpdate(staff);
            return ResultBody.success(a);
        }
        //创建账号
        user.setCompanyId(userAuth.getCompanyId());
        user.setPassword(CommonConstants.DEF_PWD);
        user.setUserType("UT_STUDENT");
        Boolean tag = sysAccountService.register(user);
        if (tag) {//创建账号成功初始化
            staff = bizService.findByMobile(user.getMobile());
            SysBalance balance = balanceService.findByUser(user.getId());
            if (ObjectUtils.isEmpty(balance)) {
                balanceService.insert(staff.getId());
            }
            Integer num = userabilityService.countByUser(staff.getId());
            if (num < 1) {
                //初始化段位等级
                userabilityService.initUserability(staff.getId());
            }
        }
        return ResultBody.success(tag);
    }


    /**
     * 更新员工信息
     */
    @ApiOperation(value = "更新员工信息", notes = "更新员工信息")
    public ResultBody editStaff(@ModelAttribute SysUserDto user) {
        SysUser oldUser = bizService.getById(user.getId());
        if (!user.getMobile().equals(oldUser.getMobile())) {//当手机号变化
            //当用户手机号发生改变时
            SysUser accountInfo = bizService.findByMobile(user.getMobile());
            if (ObjectUtils.isNotEmpty(accountInfo)) {//该手机号已注册
                return ResultBody.failed("该手机号已注册");
            }
            bizService.updateMobile(user.getId(),oldUser.getMobile(),user.getMobile());
        }
        boolean tag = bizService.saveOrUpdate(user);
        return ResultBody.success(tag);
    }

    /**
     * 企业部门列表
     */
    @ApiOperation(value = "企业部门列表", notes = "企业部门列表")
    public ResultBody getDepartment(@PathVariable String parentId) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();//企业
        SysUser comUser = bizService.getById(userAuth.getUserId());
        String companyId = String.valueOf(comUser.getCompanyId());
        List<Map<String, Object>> list = sysDeptService.selectDept(companyId, parentId);
        return ResultBody.success(list);
    }

    /**
     * 修改查询员工信息
     */
    @ApiOperation(value = "员工信息", notes = "员工信息")
    public ResultBody staffInfo(@PathVariable Long userId) {
        CriteriaQuery cq = new CriteriaQuery();
        cq.select("sex,u.id,userName,jobNo,hiredate,email,mobile,dept.deptName,u.deptId,u.idCard");
        cq.eq("u.id", userId);
        cq.createAlias("dept", "dept");
        EntityMap staff = bizService.getEntityMap(cq);
        return ResultBody.success(staff);
    }

    /**
     * 删除员工
     */
    @ApiOperation(value = "删除员工", notes = "删除员工")
    public ResultBody delByIds(@RequestParam String[] ids) {
        for (String id : ids) {
            UpdateWrapper staff = new UpdateWrapper();
            bizService.update(staff.set(true, "companyId", null).set(true, "deptId", null).set(true, "hiredate", null).eq(true, "id", id));
        }
        return ResultBody.success(true);
    }

    /**
     * hr打分
     */
    @ApiOperation(value = "hr打分", notes = "hr打分")
    public ResultBody hrGrade(@ModelAttribute UserabilityDto userability) {
        UpdateWrapper score = new UpdateWrapper();
        boolean tag = userabilityService.update(score.set(true, "hrScore", userability.getHrScore()).eq(true, "id", userability.getUserabilityId()));
        return ResultBody.success(tag);
    }


    /**
     * 添加黑名单
     */
    @ApiOperation(value = "添加企业黑名单", notes = "添加企业黑名单")
    public ResultBody addBlacklist(@PathVariable Long userId) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();//企业
        SysUser comUser = bizService.getById(userAuth.getUserId());
        String companyId = String.valueOf(comUser.getCompanyId());
        Integer num = blacklistService.count(companyId, userId);
        if (num > 0) {
            return ResultBody.failed("该员工已经被添加为黑名单，无法重复添加");
        }
        SysBlacklist blacklist = new SysBlacklist();
        blacklist.setUserId(userId);
        blacklist.setCompanyId(companyId);
        boolean tag = blacklistService.save(blacklist);
        return ResultBody.success(tag);
    }

    /**
     * 移除黑名单
     */
    @ApiOperation(value = "移除黑名单", notes = "移除黑名单")
    public ResultBody delBlacklist(@PathVariable Long userId) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();//企业
        SysUser comUser = bizService.getById(userAuth.getUserId());
        String companyId = String.valueOf(comUser.getCompanyId());
        boolean tag = blacklistService.delByUser(companyId, userId);
        return ResultBody.success(tag);
    }


    /**
     * 企业排名
     * type:1本企业排名，2所有企业内排名
     */
    @ApiOperation(value = "企业排名", notes = "企业排名")
    public ResultBody companyRank(@ModelAttribute PagerInfo pagerInfo, @ModelAttribute SysRankDto sysRankDto) {
        CriteriaQuery queryWrapper = new CriteriaQuery<EntityMap>(pagerInfo);
        if(sysRankDto.getType().equals(2)){//全部企业
            pagerInfo.setPageSize(50);
            pagerInfo.setPageNumber(1);
        }
        String sql = "b.abilityScore,d.duanName,u.userName,u.nickName,u.mobile,u.id userId,u.companyId,c.compName,dept.deptName, 20 ourCom, 20 allCom," + sysRankDto.getType() + " type";
        queryWrapper.select(sql);
        if (sysRankDto.getType().equals(1)) {
            OpenUserAuth userAuth = OpenHelper.getUserAuth();//企业
            SysUser comUser = bizService.getById(userAuth.getUserId());
            queryWrapper.eq("u.companyId", comUser.getCompanyId());
        }
        queryWrapper.eq("u.userType", "UT_STUDENT");
        queryWrapper.eq("b.abilityItemId", sysRankDto.getExamtypeId());
        queryWrapper.like("u.userName", sysRankDto.getUserName());
        queryWrapper.like("u.mobile", sysRankDto.getMobile());
        queryWrapper.isNotNull("u.companyId");
        queryWrapper.createAlias("abiltity", "b");
        queryWrapper.createAlias("dept", "dept");
        queryWrapper.createAlias("duan", "d");
        queryWrapper.createAlias("company", "c");
        queryWrapper.orderByDesc("b.abilityScore+0");
        queryWrapper.orderByDesc("d.sortOrder");
        queryWrapper.orderByAsc("u.createTime");
        PqGrid pqGrid = bizService.pageList(queryWrapper);
        List<EntityMap> list = (List<EntityMap>) pqGrid.getRows();
        //计算用户在自己公司及平台排名
        List<EntityMap> allList = userabilityService.selectuser(null, sysRankDto.getExamtypeId());
        for (EntityMap entityMap : list) {
            Integer all = 1;
            Integer user = 1;
            String userId = entityMap.get("userId").toString();
            Long companyId = entityMap.get("companyId");
            List<EntityMap> userList = userabilityService.selectuser(companyId, sysRankDto.getExamtypeId());
            for (EntityMap allRank : allList) {
                String u = allRank.get("userId").toString();
                if (userId.equals(u)) {
                    break;
                }
                ++all;
            }
            for (EntityMap userRank : userList) {
                String u = userRank.get("userId").toString();
                if (userId.equals(u)) {
                    break;
                }
                ++user;
            }
            entityMap.put("allCom", all);
            entityMap.put("ourCom", user);
        }
        return ResultBody.success(pqGrid);
    }

}
